<template>
  <el-empty v-if="dailyItemInfo.itemList.length === 0" description="暂无记录"/>

  <div v-else class="food-daily-item card-item">
    <daily-summary :date="dailyItemInfo.date"/>

    <div class="daily-list">
      <daily-card v-for="(item, index) in dailyItemInfo.itemList"
                  :key="index" :title="item.name" :content="item.category">
        <template #icon>
          <el-avatar>{{ item.category.charAt(0) }}</el-avatar>
        </template>

        <template #extra>
          <el-button type="primary" :icon="CaretRight" circle @click="selectFoodRecordClick(item)"/>
        </template>
      </daily-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { CaretRight } from '@element-plus/icons-vue'
import DailySummary from '@/components/DailySummary.vue'
import DailyCard from '@/components/DailyCard.vue'
import { defineProps, onMounted, reactive, watch } from 'vue'
import { useFoodStore } from '@/store/food.ts'
import { useRouter } from 'vue-router'
import { useAppStore } from '@/store/app.ts'
import { formatChineseDate } from 'vue3-common/utils/dateUtil'
import type { IRecord } from '@/types/food.ts'

const foodStore = useFoodStore()
const appStore = useAppStore()
const router = useRouter()

const props = defineProps({
  date: {
    required: true,
    type: String
  }
})

watch(() => props.date, () => {
  getFoodDailyByDate(props.date as string)
})

watch(() => foodStore.isRefresh, () => {
  getFoodDailyByDate(props.date as string)
})

onMounted(() => {
  getFoodDailyByDate(props.date as string)
})

const dailyItemInfo = reactive({
  date: '',
  itemList: [] as IRecord[]
})

/**
 * 根据日期获取当天的美食记录
 * @param date
 */
const getFoodDailyByDate = (date: string) => {
  if (date) {
    dailyItemInfo.date = formatChineseDate(date, 'MM月DD日 dddd')
    dailyItemInfo.itemList = []

    foodStore.recordList.forEach((item) => {
      if (item.date === date) {
        dailyItemInfo.itemList.push(item)
      }
    })
  } else {
    dailyItemInfo.itemList = []
  }
}

/**
 * 点击美食记录按钮
 * @param record 美食记录
 */
const selectFoodRecordClick = async (record: IRecord) => {
  foodStore.recordApiType = 'UPDATE'

  appStore.isShowMobileBack = true
  foodStore.currentRecord = record
  await router.push('/record/recordForm')
}
</script>

<style lang="scss">
.food-daily-item {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 5px;

  .daily-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
    overflow: auto;
  }
}
</style>
